package org.yl.db_core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description: 类型转换
 * @Author: YL
 * @CreateDate: 2018/11/10 15:08
 * @Version: 1.0
 */
@Component
public class TypeToCast implements Serializable {

    private final static Logger logger = LoggerFactory.getLogger(TypeToCast.class);

    /**
     * 生成实体类名
     *
     * @param tableName
     * @param type
     * @return
     */
    public String toClassName(String tableName, String type) {
        /**替換表名*/
        String[] tables = tableName.split("_");
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < tables.length; i++) {
            logger.info("表Name:" + tables[i]);
            result.append(toUpperCaseFirstOne(tables[i]));
        }
        result.append(type);
        String ch = toUpperCaseFirstOne(result.toString());
        logger.info("生成实体类名:, {}:", ch);
        return ch;
    }

    /**
     * 生成表名
     *
     * @param className
     * @return
     */
    public String toTableName(String className) {
        /**去除后缀名Model*/
        className = className.substring(0, className.lastIndexOf("M"));
        logger.info("类名:, {}", className);
        String[] arr = className.split("");
        StringBuffer sb = new StringBuffer();
        String result = "";
        for (int i = 0; i < arr.length; i++) {
            result = arr[i];
            char[] ch = arr[i].toCharArray();
            if (ch[0] >= 'A' && ch[0] <= 'Z') {
                if (i == 0) {
                    result = toLowerFirstOne(arr[i]);
                } else {
                    result = "_" + toLowerFirstOne(arr[i]);
                }
            }
            sb.append(result);
        }
        logger.info("生成表名:, {}", String.valueOf(sb));
        return String.valueOf(sb).toUpperCase();
    }

    /**
     * 首字母大写
     *
     * @param str
     * @return
     */
    public String toUpperCaseFirstOne(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        //logger.info("首字母大写:, {}:", String.valueOf(ch));
        return String.valueOf(ch);
    }

    /**
     * 首字母小写
     *
     * @param str
     * @return
     */
    public String toLowerFirstOne(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'A' && ch[0] <= 'Z') {
            ch[0] = (char) (ch[0] + 32);
        }
        //logger.info("首字母小写:, {}:", String.valueOf(ch));
        return String.valueOf(ch);
    }

    /**
     * 把一个字符串的第一个字母大写、效率是最高的
     *
     * @param fildeName
     * @return
     * @throws Exception
     */
    public String getMethodName(String fildeName) {
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        //logger.info("字符串的第一个字母大写:, {}:", String.valueOf(items));
        return new String(items);
    }

    /**
     * map 转成 Object数组
     *
     * @param map
     * @return
     */
    public Object[] mapToObjects(Map map) {
        Object[] objects = null;
        if (map != null) {
            Set<Map.Entry<String, Object>> entrySet = map.entrySet();
            //objects = map.entrySet().toArray(new Object[map.size()]);
            objects = map.values().toArray(new Object[map.size()]);
        } else {
            objects = new Object[0];
        }
        return objects;
    }

    /**
     * 实体类转map
     *
     * @param bean
     * @return
     * @throws IntrospectionException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public Map<String, Object> convertBeanToMap(Object bean) {
        try {
            Class type = bean.getClass();
            Map<String, Object> returnMap = new HashMap<String, Object>();
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (!propertyName.equals("class")) {
                    Method readMethod = descriptor.getReadMethod();
                    Object result = readMethod.invoke(bean, new Object[0]);
                    if (result != null) {
                        //if ("is_remove".equals(propertyName) && "0".equals(result)) {
                        //    returnMap.put(propertyName, result);
                        //}else if (!"0".equals(result)){
                            returnMap.put(propertyName, result);
                        //}

                    } else {
                        returnMap.put(propertyName, "");
                    }
                }
            }
            return returnMap;
        } catch (Exception e) {
            logger.error("实体类转map：,{}", e.getMessage());
        }
        return null;
    }


}
